package DRC;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import DRC.DRModbus.DRModbus_RTU_Master;
import DRC.DRModbus.DRModbus_TCP_Master;
import DRCOMM.DRHTTP_API;
import DRCOMM.DR_SESSION;
import DRCOMM.FJW_URI;
import DRCOMM.dr_ajax_answer;
import DRCOMM.record_data_set;

public class channel4collect{

    public int channel_id=-1;
    public String name="";
    public int dataitem_type=-1;
    public String host_ip="";
    public int port=-1;
    public int protocol=-1;
    public String path="";
    public String filename="";
    public String com="";
    public int band_rate=-1;
    public int parity=-1;
    public int stop=-1;
    public int enable=1;
    public int slave_id=1;
    public int register_type=3;
    public int address=0;
    public int count=1;
    public int run_cycle=10;
    public Date create_time=new Date();
    public int creat_text=0;
    public int IntervalTime=100;
    public ArrayList<dataItem4collect> ds4c=new ArrayList<dataItem4collect>();
    public static int data_collect_cycle=10;   //采集循环间隔时间
    public DRCDB drcdb;

    private static Map<String,Thread> channel_run_list=new HashMap<String,Thread>();

    public channel4collect(DRCDB drcdb){
        this.drcdb=drcdb;
    }

    public channel4collect(DRCDB drcdb,String name,String host_ip){
        this.drcdb=drcdb;
        this.name=name;
        this.host_ip=host_ip;
    }

    public channel4collect(int channel_id,String name,String host_ip,int port,
        int protocol){
        this.channel_id=channel_id;
        this.name=name;
        this.host_ip=host_ip;
        this.port=port;
        this.protocol=protocol;
    }

    public channel4collect(int channel_id,String name,int dataitem_type,String host_ip,int port,
        int protocol,String path,String filename,String com,int band_rate,int parity,
        int stop,int enable,int slave_id,int register_type,int address,int count
        ,int run_cycle,Date create_time,int creat_text,int IntervalTime){
        this.channel_id=channel_id;
        this.name=name;
        this.dataitem_type=dataitem_type;
        this.host_ip=host_ip;
        this.port=port;
        this.protocol=protocol;
        this.path=path;
        this.filename=filename;
        this.com=com;
        this.band_rate=band_rate;
        this.parity=parity;
        this.stop=stop;
        this.enable=enable;
        this.slave_id=slave_id;
        this.register_type=register_type;
        this.address=address;
        this.count=count;
        this.run_cycle=run_cycle;
        this.create_time=create_time;
        this.creat_text=creat_text;
        this.IntervalTime=IntervalTime;
    }

    public void report(){
        System.out.println("channel_id="+this.channel_id);
        System.out.println("name="+this.name);
        System.out.println("dataitem_type="+this.dataitem_type);
        System.out.println("host_ip="+this.host_ip);
        System.out.println("port="+this.port);
        System.out.println("protocol="+this.protocol);
        System.out.println("path="+this.path);
        System.out.println("filename="+this.filename);
        System.out.println("com="+this.com);
        System.out.println("band_rate="+this.band_rate);
        System.out.println("parity="+this.parity);
        System.out.println("stop="+this.stop);
        System.out.println("enable="+this.enable);
        System.out.println("slave_id="+this.slave_id);
        System.out.println("register_type="+this.register_type);
        System.out.println("address="+this.address);
        System.out.println("run_cycle="+this.run_cycle);
        System.out.println("create_time="+this.create_time);
        System.out.println("creat_text="+this.creat_text);
        for(dataItem4collect d4c:this.ds4c){
            d4c.report();
        }
    }

    public void set_channel_id(int channel_id){
        this.channel_id=channel_id;
    }

    public void set_path(String path,String filename){
        this.path=path;
        this.filename=filename;
    }

    public void set_com(String com,int band_rate){
        this.com=com;
        this.band_rate=band_rate;
    }

    public record_data_set read_channel4collects(){
        DRCDB db=this.drcdb;
        String sqlstr="select * from channel4collect";
        record_data_set rds=db.executeQuerySQL(sqlstr);
        return rds;
    }

    /**
     * 关联WEB API列表
     * @param api_lists
     * @param drcdb
     */
    public static void associate_actions(List<DRHTTP_API> api_lists,DRCDB drcdb) throws ClassNotFoundException{
        @SuppressWarnings("unchecked")
        Class<?> CLS=(Class<channel4collect>) Class.forName("DRC.channel4collect");
        for(Method method:CLS.getDeclaredMethods()){
            FJW_URI fjw_uri=method.getAnnotation(FJW_URI.class);
//            System.out.println(method.toString());
            if(fjw_uri!=null){
//                System.out.println(method.toString());
//                System.out.println(fjw_uri.value());
                try {
                    api_lists.add((DRHTTP_API)method.invoke(CLS,drcdb, fjw_uri.value()));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @FJW_URI(value ="channel4collect/channelList")
    public static DRHTTP_API channel_list(DRCDB drcdb,String URI){
        return new DRHTTP_API(drcdb,URI){
            @Override
            public String getResult(Map<String, Object> parameters,DR_SESSION drs){
                String content="";
                String page=this.get_parameters(parameters,"page");
                String limit=this.get_parameters(parameters,"limit");
                DRCDB db=drcdb;
                int pagesize;
                int current_page;
                if(page.equals(""))current_page=1;
                else current_page=Integer.parseInt(page);
                if(limit.equals(""))pagesize=10;
                else pagesize=Integer.parseInt(limit);
                String sqlstr="select channel_id,name,host_ip,port,com,band_rate,protocol,enable,register_type from channel4collect order by channel_id";
                sqlstr+=String.format(" limit %d,%d",pagesize*(current_page-1),pagesize);
                record_data_set rds=db.executeQuerySQL(sqlstr);
                content=record_data_set.get_answer_json_str(0,"",rds);
                return content;
            }
        };
    }

    @FJW_URI(value ="channel4collect/readChannel")
    public static DRHTTP_API read_channel4collect(DRCDB drcdb,String URI){
        return new DRHTTP_API(drcdb,URI){
            @Override
            public String getResult(Map<String, Object> parameters,DR_SESSION drs){
                String content="";
                String channel_id=this.get_parameters(parameters,"channel_id");
                DRCDB db=drcdb;
                String sqlstr="select channel_id,name,dataitem_type,host_ip,port,protocol,path,filename,com,band_rate,parity,stop,enable,slave_id,register_type,address,count,run_cycle from channel4collect";
                sqlstr+=String.format(" where channel_id=%s",channel_id);
                record_data_set rds=db.executeQuerySQL(sqlstr);
                content=record_data_set.get_answer_json_str(0,"",rds);
                return content;
            }
        };
    }

    @FJW_URI(value ="channel4collect/saveChannel")
    public static DRHTTP_API save_channel4collect(DRCDB drcdb,String URI){
        return new DRHTTP_API(drcdb,URI){
            @Override
            public String getResult(Map<String, Object> parameters,DR_SESSION drs){
                String content="";
                String channel_id=this.get_parameters(parameters,"channel_id");
                String name=this.get_parameters(parameters,"name");
                String dataitem_type=this.get_parameters(parameters,"dataitem_type");
                String host_ip=this.get_parameters(parameters,"host_ip");
                String port=this.get_parameters(parameters,"port");
                String protocol=this.get_parameters(parameters,"protocol");
                String path=this.get_parameters(parameters,"path");
                String filename=this.get_parameters(parameters,"filename");
                String com=this.get_parameters(parameters,"com");
                String band_rate=this.get_parameters(parameters,"band_rate");
                String parity=this.get_parameters(parameters,"parity");
                String stop=this.get_parameters(parameters,"stop");
                String enable=this.get_parameters(parameters,"enable");
                String slave_id=this.get_parameters(parameters,"slave_id");
                String register_type=this.get_parameters(parameters,"register_type");
                String address=this.get_parameters(parameters,"address");
                String count=this.get_parameters(parameters,"count");
                String run_cycle=this.get_parameters(parameters,"run_cycle");
                String IntervalTime=this.get_parameters(parameters,"IntervalTime");
                DRCDB db=drcdb;
                String sqlstr;
                boolean result=false;
                enable=(enable.length()>0)?"1":"0";
                String filenameNew;
                if("7".equals(protocol)){
                    filenameNew = filename+"&"+IntervalTime;
                }else {
                    filenameNew = filename;
                }
                try {
                    if(channel_id==null||channel_id==""){
                        Date now=new Date();
                        SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
                        sqlstr="insert into channel4collect(name,dataitem_type,host_ip,port,protocol,path,filename,com,band_rate,parity,stop,enable,slave_id,register_type,address,count,run_cycle,create_time) ";
                        sqlstr+=String.format(" values('%s',%s,'%s',%s,%s,'%s','%s','%s',%s,%s,%s,%s,%s,%s,%s,%s,%s,'%s')",name,dataitem_type,host_ip,port,protocol,path,filenameNew,com,band_rate,parity,stop,enable,slave_id,register_type,address,count,run_cycle,ft.format(now));
                    }else{
                        sqlstr="update channel4collect";
                        sqlstr+=String.format(" set name='%s'" , name);
                        sqlstr+=String.format(",dataitem_type=%s" , dataitem_type);
                        sqlstr+=String.format(",host_ip='%s'" , host_ip);
                        sqlstr+=String.format(",port=%s" , port);
                        sqlstr+=String.format(",protocol=%s" , protocol);
                        sqlstr+=String.format(",path='%s'" , path);
                        sqlstr+=String.format(",filename='%s'" , filenameNew);
                        sqlstr+=String.format(",com='%s'" , com);
                        sqlstr+=String.format(",band_rate=%s" , band_rate);
                        sqlstr+=String.format(",parity=%s" , parity);
                        sqlstr+=String.format(",stop=%s" , stop);
                        sqlstr+=String.format(",enable=%s" , enable);
                        sqlstr+=String.format(",slave_id=%s" , slave_id);
                        sqlstr+=String.format(",register_type=%s" , register_type);
                        sqlstr+=String.format(",address=%s" , address);
                        sqlstr+=String.format(",count=%s" , count);
                        sqlstr+=String.format(",run_cycle=%s" , run_cycle);
                        sqlstr+=String.format(" where channel_id=%s" , channel_id);
                    }
                    System.out.println(sqlstr);
                    result=db.executeUpdateSQL(sqlstr);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println(result);
                if(result){
                    content=dr_ajax_answer.sample_json_string(0,"");
                }else{
                    content=dr_ajax_answer.sample_json_string(1,"保存失败！");
                }
                return content;
            }
        };
    }

    @FJW_URI(value ="channel4collect/delChannel")
    public static DRHTTP_API del_channel4collect(DRCDB drcdb,String URI){
        return new DRHTTP_API(drcdb,URI){
            @Override
            public String getResult(Map<String, Object> parameters,DR_SESSION drs){
                String content="";
                String channel_id=this.get_parameters(parameters,"channel_id");
                boolean result=false;
                DRCDB db=drcdb;
                String sqlstr;
                sqlstr="delete from channel4collect";
                sqlstr+=String.format(" where channel_id=%s" , channel_id);
                result=db.executeUpdateSQL(sqlstr);
                sqlstr="delete from dataItem4collect";
                sqlstr+=String.format(" where channel_id=%s" , channel_id);
                result=db.executeUpdateSQL(sqlstr);
                if(result){
                    content=dr_ajax_answer.sample_json_string(0,"");
                }else{
                    content=dr_ajax_answer.sample_json_string(1,"删除失败！");
                }
                return content;
            }
        };
    }

    @FJW_URI(value ="channel4collect/checkChannelState")
    public static DRHTTP_API checkChannel4collectState(DRCDB drcdb,String URI){
        return new DRHTTP_API(drcdb,URI){
            @Override
            public String getResult(Map<String, Object> parameters,DR_SESSION drs){
                String content="";
                String channel_id=this.get_parameters(parameters,"channel_id");
                if(channel_run_list.containsKey("channel4collect_"+channel_id)){
                    Thread t=channel_run_list.get("channel4collect_"+channel_id);
                    if(t.isAlive()){
                        content=dr_ajax_answer.sample_json_string(0,"通道已运行");
                    }else{
                        content=dr_ajax_answer.sample_json_string(1,"通道未运行");
                    }
                }else{
                    content=dr_ajax_answer.sample_json_string(1,"通道未运行");
                }
                return content;
            }
        };
    }

    public static ArrayList<channel4collect> read_channels4collect(DRCDB drcdb){
        ArrayList<channel4collect> channel_list=new ArrayList<channel4collect>();
        String sqlstr;
        String sqlstr_d4c;
        int channel_id;
        String name;
        int dataitem_type;      //数据点类型，0：公用数据点（即系统默认的点表），1：专用数据点，与通道对应
        String host_ip;         //主机地址，针对modbus tcp等基于IP网络协议的对端地址
        int port;               //端口号，与上面主机对应的端口号
        int protocol;           //协议类型
        String path;            //文件路径
        String filename;        //文件名
        String com;             //串口名，针对使用串口的协议
        int band_rate;          //波特率
        int parity;          //波特率
        int stop;          //波特率
        int enable;            //是否启用
        int slave_id;           //slave ID
        int register_type;      //寄存器类型
        int function_code=3;      //功能码，针对modbus协议
        int address;            //地址
        int count;              //数据量，针对modbus协议
        int run_cycle;          //运行周期
        Date create_time;        //创建时间
        int creat_text;
        int IntervalTime=100;
        record_data_set rds;    //数据表集合对象，用于读取采集通道数据
        sqlstr="select channel_id,name,dataitem_type,host_ip,port,protocol,path,filename,com,band_rate,parity,stop,enable,slave_id,register_type,address,count,run_cycle,create_time,creat_text from channel4collect";
        rds=drcdb.executeQuerySQL(sqlstr);
        SimpleDateFormat ft=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for(int channel_index=0;channel_index<rds.datas.size();channel_index++){
            if("7".equals(rds.datas.get(channel_index).get("protocol"))){
                if(rds.datas.get(channel_index).get("filename").split("&").length==2){
                    filename=rds.datas.get(channel_index).get("filename").split("&")[0];
                    IntervalTime=Integer.parseInt(rds.datas.get(channel_index).get("filename").split("&")[1]);
                }else{
                    filename = "";
                    IntervalTime=100;
                }
            }else{
                filename=rds.datas.get(channel_index).get("filename");
            }
            channel_id=Integer.parseInt(rds.datas.get(channel_index).get("channel_id"));
            name=rds.datas.get(channel_index).get("name");
            dataitem_type=Integer.parseInt(rds.datas.get(channel_index).get("dataitem_type"));
            host_ip=rds.datas.get(channel_index).get("host_ip");
            port=Integer.parseInt(rds.datas.get(channel_index).get("port"));
            protocol=Integer.parseInt(rds.datas.get(channel_index).get("protocol"));
            path=rds.datas.get(channel_index).get("path");
            com=rds.datas.get(channel_index).get("com");
            band_rate=Integer.parseInt(rds.datas.get(channel_index).get("band_rate"));
            parity=Integer.parseInt(rds.datas.get(channel_index).get("parity"));
            stop=Integer.parseInt(rds.datas.get(channel_index).get("stop"));
            enable=Integer.parseInt(rds.datas.get(channel_index).get("enable"));
            slave_id=Integer.parseInt(rds.datas.get(channel_index).get("slave_id"));
            register_type=Integer.parseInt(rds.datas.get(channel_index).get("register_type"));
            address=Integer.parseInt(rds.datas.get(channel_index).get("address"));
            count=Integer.parseInt(rds.datas.get(channel_index).get("count"));
            run_cycle=Integer.parseInt(rds.datas.get(channel_index).get("run_cycle"));
            create_time=new Date();
            try {
                create_time = ft.parse(rds.datas.get(channel_index).get("create_time"));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            creat_text=Integer.parseInt(rds.datas.get(channel_index).get("creat_text"));
            channel4collect ch=new channel4collect(channel_id,name,dataitem_type,host_ip,port,
                protocol,path,filename,com,band_rate,parity,stop,enable,slave_id,register_type,
                address,count,run_cycle,new Date(),creat_text,IntervalTime);
            sqlstr_d4c="select * from dataItem4collect ";
            sqlstr_d4c+=" where channel_id="+channel_id;
            sqlstr_d4c+=" order by dataItem_id";
            record_data_set rds_d4c=drcdb.executeQuerySQL(sqlstr_d4c);
            for(Map<String,String> data:rds_d4c.datas){
                int dataItem_id=Integer.parseInt(data.get("dataItem_id"));
                int slave_id_d4c=-1;
                if(!data.get("slave_id").equals(""))
                    slave_id_d4c=Integer.parseInt(data.get("slave_id"));
                int register_type_d4c=-1;
                if(!data.get("register_type").equals(""))
                    register_type_d4c=Integer.parseInt(data.get("register_type"));
                int data_index_d4c=Integer.parseInt(data.get("data_index"));
                int address_d4c=Integer.parseInt(data.get("address"));
                String label_d4c=null;
                if(!data.get("label").equals(""))
                    label_d4c=data.get("label");
                int data_type_d4c=-1;
                if(!data.get("data_type").equals(""))
                    data_type_d4c=Integer.parseInt(data.get("data_type"));
                float coefficient_d4c=-1.0f;
                if(!data.get("coefficient").equals(""))
                    coefficient_d4c=Float.parseFloat(data.get("coefficient"));
                int negation_d4c=-1;
                if(!data.get("negation").equals(""))
                    negation_d4c=Integer.parseInt(data.get("negation"));
                int BCD_d4c=-1;
                if(!data.get("BCD").equals(""))
                    BCD_d4c=Integer.parseInt(data.get("BCD"));
                int ABS_d4c=-1;
                if(!data.get("ABS").equals(""))
                    ABS_d4c=Integer.parseInt(data.get("ABS"));
                float base_value_d4c=-1.0f;
                if(!data.get("base_value").equals(""))
                    base_value_d4c=Float.parseFloat(data.get("base_value"));
                String introduction_d4c=null;
                if(!data.get("introduction").equals(""))
                    introduction_d4c=data.get("introduction");
                String data_table_d4c=null;
                if(!data.get("data_table").equals(""))
                    data_table_d4c=data.get("data_table");
                String field_d4c=null;
                if(!data.get("field").equals(""))
                    field_d4c=data_table_d4c=data.get("field");
                float value_d4c=-1.0f;
                if(!data.get("value").equals(""))
                    value_d4c=Float.parseFloat(data.get("value"));
                Date timestamp_d4c=new Date();
                if(!data.get("timestamp").equals("")){
                    try {
                        timestamp_d4c = ft.parse(data.get("timestamp"));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                Date create_time_d4c=new Date();
                if(!data.get("create_time").equals("")){
                    try {
                        create_time_d4c = ft.parse(data.get("create_time"));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                ch.ds4c.add(new dataItem4collect(channel_id, dataItem_id, slave_id_d4c, 
                register_type_d4c, data_index_d4c, address_d4c, label_d4c, data_type_d4c, 
                coefficient_d4c, negation_d4c, BCD_d4c, ABS_d4c, base_value_d4c, introduction_d4c, 
                data_table_d4c, field_d4c, value_d4c, timestamp_d4c, create_time_d4c));
            }
            channel_list.add(ch);
        }
        return channel_list;
    }

    public static void auto_run_channel4collect(DRCDB drcdb){
        String sqlstr;
        int channel_id;
        String name;
        int dataitem_type;      //数据点类型，0：公用数据点（即系统默认的点表），1：专用数据点，与通道对应
        String host_ip;         //主机地址，针对modbus tcp等基于IP网络协议的对端地址
        int port;               //端口号，与上面主机对应的端口号
        String com;             //串口名，针对使用串口的协议
        int band_rate;          //波特率
        int parity;          //波特率
        int stop;          //波特率
        int slave_id;           //slave ID
        int register_type;      //寄存器类型
        int function_code=3;      //功能码，针对modbus协议
        int address;            //地址
        int count;              //数据量，针对modbus协议
        int run_cycle;          //运行周期
        int IntervalTime;
        record_data_set rds;    //数据表集合对象，用于读取采集通道数据
        //从采集通道中查询启动的通道数据
        sqlstr="select channel_id,name,dataitem_type,host_ip,port,protocol,path,filename,com,band_rate,parity,stop,slave_id,register_type,address,count,run_cycle from channel4collect where enable=1";
        rds=drcdb.executeQuerySQL(sqlstr);
        for(int channel_index=0;channel_index<rds.datas.size();channel_index++){
            channel_id=Integer.parseInt(rds.datas.get(channel_index).get("channel_id"));  //通道id
            name=rds.datas.get(channel_index).get("name");  //通道名
            dataitem_type=Integer.parseInt(rds.datas.get(channel_index).get("dataitem_type"));  //数据点类型，公用/专用
            host_ip=rds.datas.get(channel_index).get("host_ip");  //对端ip
            port=Integer.parseInt(rds.datas.get(channel_index).get("port"));  //对端端口
            com=rds.datas.get(channel_index).get("com");  //本地ip或本地串口
            band_rate=Integer.parseInt(rds.datas.get(channel_index).get("band_rate")); //本地端口或波特率
            parity=Integer.parseInt(rds.datas.get(channel_index).get("parity"));  //奇偶校验
            stop=Integer.parseInt(rds.datas.get(channel_index).get("stop"));  //停止位
            slave_id=Integer.parseInt(rds.datas.get(channel_index).get("slave_id"));  //从站id
            register_type=Integer.parseInt(rds.datas.get(channel_index).get("register_type"));  //线圈状态
            // 暂时仅处理输入寄存器和保持寄存器
            // 2022年12月19日 罗继东
            if(register_type==3)
                function_code=4;
            else if(register_type==4)
                function_code=3;
            else if(register_type==1)
                function_code=1;
            else if(register_type==2)
                function_code=2;
            address=Integer.parseInt(rds.datas.get(channel_index).get("address"));  //地址
            count=Integer.parseInt(rds.datas.get(channel_index).get("count"));  //数量
            run_cycle=Integer.parseInt(rds.datas.get(channel_index).get("run_cycle"));  //运行周期
            switch(Integer.parseInt(rds.datas.get(channel_index).get("protocol"))){  //协议
                case 6:
                    try {
                        DRModbus_TCP_Master dtm=new DRModbus_TCP_Master(
                            drcdb, host_ip, port, channel_id, name, 
                            function_code, slave_id, address, count, 
                            dataitem_type,run_cycle);
                        dtm.start();
                        Thread.sleep(100);
                        if(dtm.isAlive())
                            channel_run_list.put("channel4collect_"+channel_id,dtm);
                    } catch (Exception e) {
                    }
                    break;
                case 7:
                    try {
                        if(rds.datas.get(channel_index).get("filename").split("&").length==2){
                            IntervalTime = Integer.parseInt(rds.datas.get(channel_index).get("filename").split("&")[1]);
                        }else {
                            IntervalTime = 100;
                        }
                        DRModbus_RTU_Master drm=new DRModbus_RTU_Master(
                            drcdb, com,band_rate,parity,stop,
                            channel_id, name, 
                            function_code, slave_id, address, count, 
                            dataitem_type,run_cycle,IntervalTime);
                        drm.start();
                        Thread.sleep(100);
                        if(drm.isAlive())
                            channel_run_list.put("channel4collect_"+channel_id,drm);
                    } catch (Exception e) {
                        System.out.println("Modbus RTU collect channel run error!");
                    }
                    break;
                default:
            }
        }
    }

    @FJW_URI(value ="channel4collect/runChannel")
    public static DRHTTP_API run_channel4collect(DRCDB drcdb,String URI){
        return new DRHTTP_API(drcdb,URI){
            @Override
            public String getResult(Map<String, Object> parameters,DR_SESSION drs){
                String content="";
                String channel_id=this.get_parameters(parameters,"channel_id");
                String name;
                int dataitem_type;      //数据点类型，0：公用数据点（即系统默认的点表），1：专用数据点，与通道对应
                String host_ip;         //主机地址，针对modbus tcp等基于IP网络协议的对端地址
                int port;               //端口号，与上面主机对应的端口号
                String com;             //串口名，针对使用串口的协议
                int band_rate;          //波特率
                int parity;          //波特率
                int stop;          //波特率
                int slave_id;           //slave ID
                int register_type;      //寄存器类型
                int function_code;      //功能码，针对modbus协议
                int address;            //地址
                int count;              //数据量，针对modbus协议
                int run_cycle;          //运行周期
                int IntervalTime;
                String sqlstr="select channel_id,name,dataitem_type,host_ip,port,protocol,path,filename,com,band_rate,slave_id,register_type,address,count,run_cycle from channel4collect where enable=1";
                sqlstr+=String.format(" and channel_id=%s",channel_id);
                record_data_set rds=drcdb.executeQuerySQL(sqlstr);
                if(rds.datas.size()>0){
                    name=rds.datas.get(0).get("name");
                    dataitem_type=Integer.parseInt(rds.datas.get(0).get("dataitem_type"));
                    host_ip=rds.datas.get(0).get("host_ip");
                    port=Integer.parseInt(rds.datas.get(0).get("port"));
                    com=rds.datas.get(0).get("com");
                    band_rate=Integer.parseInt(rds.datas.get(0).get("band_rate"));
                    try {
                        parity=Integer.parseInt(rds.datas.get(0).get("parity"));
                        stop=Integer.parseInt(rds.datas.get(0).get("stop"));
                        slave_id=Integer.parseInt(rds.datas.get(0).get("slave_id"));
                    } catch (Exception e) {
                        parity=0;
                        stop=1;
                        slave_id=1;
                    }
                    register_type=Integer.parseInt(rds.datas.get(0).get("register_type"));                
                    if(register_type==3)function_code=4;
                    else function_code=3;
                    address=Integer.parseInt(rds.datas.get(0).get("address"));
                    // 为处理本地端口问题，将104采集协议的波特率设置为本地端口
                    band_rate=Integer.parseInt(rds.datas.get(0).get("band_rate"));
                    count=Integer.parseInt(rds.datas.get(0).get("count"));
                    run_cycle=Integer.parseInt(rds.datas.get(0).get("run_cycle"));
                    switch(Integer.parseInt(rds.datas.get(0).get("protocol"))){
                        case 6:
                            try {
                                DRModbus_TCP_Master dtm=new DRModbus_TCP_Master(
                                    drcdb, host_ip, port, Integer.parseInt(channel_id), name, 
                                    function_code, slave_id, address, count, 
                                    dataitem_type,run_cycle);
                                dtm.start();
                                Thread.sleep(100);
                                if(dtm.isAlive()){
                                    channel_run_list.put("channel4collect_"+channel_id,dtm);
                                    content=dr_ajax_answer.sample_json_string(0,"线程启动！");
                                }else{
                                    content=dr_ajax_answer.sample_json_string(1,"启动失败！");
                                }
                            } catch (Exception e) {
                                content=dr_ajax_answer.sample_json_string(1,"启动失败！");
                                e.printStackTrace();
                            }
                            break;
                        case 7:
                            try {
                                if(rds.datas.get(0).get("filename").split("&").length==2){
                                    IntervalTime = Integer.parseInt(rds.datas.get(0).get("filename").split("&")[1]);
                                }else {
                                    IntervalTime = 100;
                                }
                                DRModbus_RTU_Master drm=new DRModbus_RTU_Master(
                                    drcdb, com,band_rate,parity,stop,
                                    Integer.parseInt(channel_id), name, 
                                    function_code, slave_id, address, count, 
                                    dataitem_type,run_cycle,IntervalTime);
                                drm.start();
                                Thread.sleep(100);
                                if(drm.isAlive()){
                                    channel_run_list.put("channel4collect_"+channel_id,drm);
                                    content=dr_ajax_answer.sample_json_string(0,"线程启动！");
                                }else{
                                    content=dr_ajax_answer.sample_json_string(1,"启动失败！");
                                }
                            } catch (Exception e) {
                                content=dr_ajax_answer.sample_json_string(1,"启动失败！");
                            }
                            break;
                        default:
                    }
                }else{
                    content=dr_ajax_answer.sample_json_string(1,"错误操作，未找到该通道，或该通道未启用");
                }
                return content;
            }
        };
    }

    @FJW_URI(value ="channel4collect/stopChannel")
    public static DRHTTP_API stop_channel4collect(DRCDB drcdb,String URI){
        return new DRHTTP_API(drcdb,URI){
            @Override
            public String getResult(Map<String, Object> parameters,DR_SESSION drs){
                String content="";
                String channel_id=this.get_parameters(parameters,"channel_id");
                if(channel_run_list.containsKey("channel4collect_"+channel_id)){
                    Thread t=channel_run_list.get("channel4collect_"+channel_id);
                    String sqlstr="select channel_id,protocol from channel4collect";
                    boolean result=false;
                    sqlstr+=String.format(" where channel_id=%s",channel_id);
                    record_data_set rds=drcdb.executeQuerySQL(sqlstr);
                    if(rds.datas.size()>0){
                        if(channel_run_list.containsKey("channel4collect_"+channel_id)){
                            if(t.isAlive()){
                                if(rds.datas.get(0).get("protocol").equals("6")){
                                    try {
                                        DRModbus_TCP_Master dtm=(DRModbus_TCP_Master) t;
                                        dtm.runMark=false;
                                        result=true;
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                                if(rds.datas.get(0).get("protocol").equals("7")){
                                    try {
                                        DRModbus_TCP_Master dtm=(DRModbus_TCP_Master) t;
                                        dtm.runMark=false;
                                        result=true;
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                                t.interrupt();
                                channel_run_list.remove("channel4collect_"+channel_id);
                                System.out.println(String.format("[%s]",rds.datas.get(0).get("protocol")));
                                if(result){
                                    t=null;
                                    System.gc();
                                    content=dr_ajax_answer.sample_json_string(0,"通道已停止");                  
                                }else{
                                    content=dr_ajax_answer.sample_json_string(1,"操作失败！");                  
                                }
                            }else{
                                content=dr_ajax_answer.sample_json_string(1,"通道未运行");                  
                            }

                        }else{
                            content=dr_ajax_answer.sample_json_string(1,"错误操作！！未找到该通道进程！");
                        }
                    }
                }

                return content;
            }
        };
    }
    
    public static void main(String[] args){
        DRCDB drcdb=new DRCDB();
        channel4collect c4c=new channel4collect(drcdb);
        record_data_set rds=c4c.read_channel4collects();
        // for(Map<String, String> row:rds.datas){
        //     System.out.println(row.get("channel4collect"));
        // }
        System.out.println(record_data_set.get_answer_json_str(0,"",rds));
    }
}